package com.fate.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fate.domain.Prod;
import com.fate.domain.ProdComm;
import com.fate.domain.ProdTagReference;
import com.fate.domain.Sku;
import com.fate.mapper.ProdMapper;
import com.fate.service.ProdCommService;
import com.fate.service.ProdService;
import com.fate.service.ProdTagReferenceService;
import com.fate.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Flux;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@CacheConfig(cacheNames = "com.fate.service.impl.ProdServiceImpl")
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService {

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private ProdCommService prodCommService;

    /**
     * 上架商品
     * 1.操作prod
     * 2.操作sku
     * 3.tag_reference
     *
     * @param
     * @param prod
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(Prod prod) {
        log.info("新增商品{}", JSON.toJSONString(prod));
        prod.setCreateTime(new Date());
        prod.setUpdateTime(new Date());
        if (prod.getStatus().equals(1)) {
            prod.setPutawayTime(new Date());
        }
        prod.setSoldNum(0);
        prod.setVersion(0);
        prod.setShopId(1L);
        //拿到配送方式
        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        String deliveryMode = JSON.toJSONString(deliveryModeVo);
        //放到prod的配送属性里面去
        prod.setDeliveryMode(deliveryMode);
        //插入prod 表
        int insert = prodMapper.insert(prod);
        if (insert > 0) {
            //处理sku
            handlerSku(prod.getSkuList(), prod.getProdId());
            //处理标签分组
            this.handlerTagReference(prod.getTagList(), prod.getProdId());
        }
        return insert > 0;
    }

    /**
     * 处理标签分组关系表
     * 商品和标签是多对多的关系
     * Transactional 操作本质是什么？ conn.doCommit  doRollback
     * Spring的只是把数据库的托管了  9 大场景
     * 1.如果数据库不支持事务 这个注解就失效了
     * 2.当前调用对象不是代理对象
     *
     * @param tagList
     * @param prodId
     */
    private void handlerTagReference(List<Long> tagList, Long prodId) {
        if (CollectionUtils.isEmpty(tagList)) {
            return;
        }
        ArrayList<ProdTagReference> prodTagReferences = new ArrayList<>(tagList.size() * 2);
        //循环标签分组id的集合
        tagList.forEach(tagId -> {
            ProdTagReference prodTagReference = new ProdTagReference();
            prodTagReference.setShopId(1L);
            prodTagReference.setCreateTime(new Date());
            prodTagReference.setTagId(tagId);
            prodTagReference.setProdId(prodId);
            prodTagReference.setStatus(true);
            prodTagReferences.add(prodTagReference);
        });
        //操作数据库
        prodTagReferenceService.saveBatch(prodTagReferences);
    }

    /**
     * 处理sky
     *
     * @param skuList
     * @param prodId
     */
    private void handlerSku(List<Sku> skuList, Long prodId) {
        if (CollectionUtils.isEmpty(skuList)) {
            return;
        }
        //循环sku集合 设置prodId
        skuList.forEach(sku -> {
            sku.setProdId(prodId);
            sku.setVersion(0);
            sku.setRecTime(new Date());
            sku.setUpdateTime(new Date());
            sku.setActualStocks(sku.getStocks());
            sku.setIsDelete(0);
        });
        //操作插入sku
        skuService.saveBatch(skuList);
    }

    /**
     * 根据时间区间查询总条数
     *
     * @param t1
     * @param t2
     * @return
     */
    @Override
    public Integer getTotal(Date t1, Date t2) {
        Integer count = prodMapper.selectCount(new LambdaQueryWrapper<Prod>()
                .between(t1 != null && t2 != null, Prod::getUpdateTime, t1, t2)
        );
        return count;
    }

    /**
     * 根据时间区间分页查询商品对象
     *
     * @param page
     * @param t1
     * @param t2
     * @return
     */
    @Override
    public List<Prod> findProdPageByTime(Page<Prod> page, Date t1, Date t2) {
        IPage<Prod> prodPage = prodMapper.selectPage(page, new LambdaQueryWrapper<Prod>()
                .between(t1 != null && t2 != null, Prod::getUpdateTime, t1, t2)
        );
        //判断一下 是否有数据
        List<Prod> prodList = prodPage.getRecords();
        if (CollectionUtils.isEmpty(prodList)) {
            return Collections.emptyList();
        }
        //如果有数据
        //1.处理tagList 商品和标签是多对多的关系 有一个中间表
        //拿到prodIds
        List<Long> prodIds = prodList.stream()
                .map(Prod::getProdId)
                .collect(Collectors.toList());
        //查询tag_reference
        List<ProdTagReference> tagReferenceList = prodTagReferenceService.list(new LambdaQueryWrapper<ProdTagReference>()
                .in(ProdTagReference::getProdId, prodIds)
        );
        if (!CollectionUtils.isEmpty(tagReferenceList)) {
            //组装数据
            //循环商品集合 tagId
            prodList.forEach(prod -> {
                List<Long> tagList = tagReferenceList.stream()
                        .filter(prodTagReference -> prodTagReference.getProdId().equals(prod.getProdId()))
                        .map(ProdTagReference::getTagId)
                        .collect(Collectors.toList());
                prod.setTagList(tagList);
            });
        }
        // 处理评论
        List<ProdComm> prodCommList = prodCommService.list(new LambdaQueryWrapper<ProdComm>()
                .in(ProdComm::getProdId, prodIds)
        );
        prodList.forEach(prod -> {
            Boolean flag = true;
            if (!CollectionUtils.isEmpty(prodCommList)) {
                // 拿到一个商品的所有评论
                List<ProdComm> oneProdAllComm = prodCommList.stream()
                        .filter(prodComm -> prodComm.getProdId().equals(prod.getProdId()))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(oneProdAllComm)) {

                    // 拿到总评数
                    int totalComm = oneProdAllComm.size();
                    // 拿到好评数
                    int goodsComm = (int) oneProdAllComm.stream()
                            .filter(prodComm -> prodComm.getEvaluate().equals(0))
                            .count();
                    // 计算好评率 BigDecimal
                    if (goodsComm != 0) {

                        // 只要 这个商品对应有评论 就设置false
                        flag = false;

                        BigDecimal goodsLv = new BigDecimal(goodsComm)
                                .divide(new BigDecimal(totalComm), 2, BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal(100));
                        // 设置到商品中
                        prod.setPositiveRating(goodsLv);
                        prod.setPraiseNumber((long) goodsComm);
                    }
                }
            }
            if (flag) {
                prod.setPraiseNumber(0L);
                prod.setPositiveRating(BigDecimal.ZERO);
            }
        });
        return prodList;
    }


    /**
     * 根据商品的id查询商品的信息包含sku的集合
     */
    @Override
    @Cacheable(key ="#id" )
    public Prod getById(Serializable id) {
        Prod prod = prodMapper.selectById(id);
        if (ObjectUtils.isEmpty(prod)){
            throw new IllegalArgumentException("商品id不存在");
        }
        //查询sku集合 状态 库存
        List<Sku> list = skuService.list(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, id)
                .eq(Sku::getStatus, 1)
                .orderByDesc(Sku::getPrice)
        );
        prod.setSkuList(list);
        return  prod;
    }

    /**
     * 修改库存
     * @param map
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void changeStock(Map<String, Map<Long, Integer>> map) {
        //加有个redis 分布式锁
        Map<Long, Integer> prodMap = map.get("prod");
        //需要先拿到prodIds 查询prod集合
        Set<Long> prodIds = prodMap.keySet();
        //查询数据库 拿到prod集合
        List<Prod> prodList = prodMapper.selectBatchIds(prodIds);
        if (CollectionUtils.isEmpty(prodList)){
            throw new IllegalArgumentException("修改prod库存 Prod集合为空");
        }
        //修改prod的库存
        prodList.forEach(prod -> {
            //从map里面去到对应的库存
            Long prodId = prod.getProdId();
            Integer count = prodMap.get(prodId);
           int finalStock=  prod.getTotalStocks()+count;
           if (finalStock<0){
               throw new IllegalArgumentException("prod的"+prod.getProdId()+"库存不足");
           }
            //减库存
            prod.setTotalStocks(finalStock);
            //--得正;
            prod.setTotalStocks(prod.getSoldNum()-count);
            prod.setUpdateTime(new Date());
        });
        //更新
        super.saveOrUpdateBatch(prodList);
        //处理sku
        Map<Long, Integer> skuMap = map.get("sku");
        Set<Long> skuIds = skuMap.keySet();
        List<Sku> skuList = (List<Sku>) skuService.listByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)){
            throw new IllegalArgumentException("修改sku库存,sku集合为空");
        }
        skuList.forEach(sku -> {
            Integer count = skuMap.get(sku.getSkuId());
            int finalCount = sku.getActualStocks()+count;
            if (finalCount<0){
                throw new IllegalArgumentException("sku的"+sku.getSkuId()+"库存不足");
            }
            sku.setActualStocks(finalCount);
            sku.setUpdateTime(new Date());
        });
        skuService.saveOrUpdateBatch(skuList);
    }
}




